package com.dingreading.cloud.subject.service.impl;

import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.util.IpUtil;
import com.dingreading.cloud.subject.dto.SubjectsFileDto;
import com.dingreading.cloud.subject.entity.SubjectLessonLog;
import com.dingreading.cloud.subject.entity.Subjects;
import com.dingreading.cloud.subject.entity.SubjectsFiles;
import com.dingreading.cloud.subject.entity.table.SubjectsTableDef;
import com.dingreading.cloud.subject.mapper.SubjectsMapper;
import com.dingreading.cloud.subject.service.SubjectLessonLogService;
import com.dingreading.cloud.subject.service.SubjectsFilesService;
import com.dingreading.cloud.subject.service.SubjectsService;
import com.dingreading.cloud.subject.util.CdnUrlUtil;
import com.dingreading.cloud.subject.util.SubjectUtil;
import com.mybatisflex.core.query.QueryCondition;
import com.mybatisflex.core.query.QueryWrapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 服务层实现。
 *
 * @author Administrator
 * @since 2023-11-22
 */
@Service
public class SubjectsServiceImpl extends BaseServiceImpl<SubjectsMapper, Subjects, SubjectsTableDef> implements SubjectsService {

    @Override
    protected SubjectsTableDef getTable() {
        return SubjectsTableDef.subjects;
    }

    @Resource
    private CdnUrlUtil cdnUrlUtil;
    @Resource
    private SubjectsFilesService subjectsFilesService;
    @Resource
    private SubjectLessonLogService subjectLessonLogService;


    @Override
    public List<Subjects> getMainSubjectsV3(List<Long> subjectIdList) {
        QueryCondition condition = QueryCondition.createEmpty();
        condition.and(table.parentId.eq(0L))
                .and(table.enabled.eq(1));
        if (CollectionUtils.isNotEmpty(subjectIdList)) {
            condition.and(table.id.in(subjectIdList));
        }

        QueryWrapper wrapper = QueryWrapper.create()
                .where(condition)
                .orderBy(table.showOrder.asc());

        return getMapper().selectListByQuery(wrapper);
    }

    @Override
    public List<Subjects> getChildSubjectsV2(Long mainId) {
        QueryCondition condition = QueryCondition.createEmpty();
        condition.and(table.parentId.ne(0L))
                .and(table.subjectMainId.eq(mainId))
                .and(table.enabled.eq(1));

        QueryWrapper wrapper = QueryWrapper.create()
                .where(condition)
                .orderBy(table.levelIndex.asc(), table.subjectOrder.asc());

        return getMapper().selectListByQuery(wrapper);
    }

    @Override
    public List<Subjects> dxhListByMainId(long mainId) {
        QueryCondition condition = table.subjectMainId.eq(mainId)
                .and(table.dxhEnabled.eq(1));
        QueryWrapper wrapper = QueryWrapper.create()
                .where(condition)
                .orderBy(table.subjectOrder.asc());
        return getMapper().selectListByQuery(wrapper);
    }

    @Override
    public R<Object> getDownloadUrl(
            HttpServletRequest request, String corpUid, String storeUid, String storeName, String staffUid, String staffName, Long id
    ) {
        if (id == null)
            return R.fail("文件id参数缺少！");
        SubjectsFiles subjectsFiles = subjectsFilesService.getById(id);
        if (subjectsFiles == null)
            return R.fail("文件信息获取失败！");

        String dataUrl = subjectsFiles.getFileUrl();
        if (StringUtils.isBlank(dataUrl))
            return R.fail("没有可下载的资料");

        if (subjectsFiles.getViewType().equals(2)) {
            // 防暴击下载
            R<Object> downloadR = subjectLessonLogService.preventDuplicateDownload(
                    storeUid, staffUid, subjectsFiles.getSubjectsId(), subjectsFiles.getId(), subjectsFiles.getFileType()
            );
            if (R.isError(downloadR))
                return downloadR;
        }

        String cdnUrl = null;
        if (StringUtils.isNotBlank(dataUrl)) {
            R<String> r = cdnUrlUtil.getCdnUrl(request, dataUrl);
            if (R.isError(r))
                return R.fail(r.getMsg());
            cdnUrl = r.getData();
        }

        // 下载资料记录
        String ip = IpUtil.getIpAddr(request);
        SubjectLessonLog log = SubjectUtil.saveSubjectLog(
                corpUid, storeUid, staffUid, staffName, ip, subjectsFiles.getSubjectsId(), subjectsFiles.getId(), subjectsFiles.getFileType()
        );
        subjectLessonLogService.saveOrUpdate(log);
        return R.ok(cdnUrl);
    }

    @Override
    public R<Object> getSubjectFile(
            HttpServletRequest request, String corpUid, String storeUid, String storeName, String staffUid, String staffName, Long id
    ) {
        if (StringUtils.isBlank(corpUid) || StringUtils.isBlank(storeUid) || StringUtils.isBlank(staffUid))
            return R.fail("门店参数缺少！");
        if (id == null)
            return R.fail("文件id参数缺少！");
        SubjectsFileDto data = subjectsFilesService.dtoBySubjectId(id);
        if (data == null)
            return R.fail("文件信息获取失败！");

        String fileUrl = data.getFileUrl();
        if (StringUtils.isBlank(fileUrl))
            return R.fail("没有可下载的资料");

        if (data.getViewType().equals(2)) {
            // 防暴击下载
            R<Object> downloadR = subjectLessonLogService.preventDuplicateDownload(
                    storeUid, staffUid, data.getSubjectsId(), data.getId(), data.getFileType()
            );
            if (R.isError(downloadR))
                return downloadR;
        }

        String cdnUrl = "";
        if (StringUtils.isNotBlank(fileUrl)) {
            R<String> r = cdnUrlUtil.getCdnUrl(request, fileUrl);
            if (R.isError(r))
                return R.fail(r.getMsg());
            cdnUrl = r.getData();
        }
        data.setCdnUrl(cdnUrl);

        // 下载资料记录
        String ip = IpUtil.getIpAddr(request);
        SubjectLessonLog log = SubjectUtil.saveSubjectLog(
                corpUid, storeUid, staffUid, staffName, ip, data.getSubjectsId(), data.getId(), data.getFileType()
        );
        subjectLessonLogService.saveOrUpdate(log);

        return R.ok(data);
    }


}
